import fetch from 'cross-fetch';

const header = {
  accept: 'application/json',
  'X-API-Key':
    'ccnC8jVvuyrGHdUtdqszmuSPKCVMhF7nI3qYEsU0tKXlVSQsndhyUB8QYD2vwHOQ',
};

export const sleep = (ms) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

export const getWalletETH = async (address, chain = 'eth') => {
  return new Promise(async (resolve) => {
    const resList = await fetch(
      `https://deep-index.moralis.io/api/v2/${address}/balance?chain=${chain}`,
      {
        headers: header,
        method: 'GET',
      },
    );
    const data: any = await resList.json();
    resolve(Number(data.balance) / 1000000000000000000);
  });
};

export const getWalletWETH = async (address, chain = 'eth') => {
  return new Promise(async (resolve) => {
    const wethResList = await fetch(
      `https://deep-index.moralis.io/api/v2/${address}/erc20?chain=${chain}&token_addresses=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2`,
      {
        headers: header,
        method: 'GET',
      },
    );
    const wethResListData: any = await wethResList.json();
    resolve(
      wethResListData.length === 0
        ? 0
        : wethResListData[0]['balance'] / 1000000000000000000,
    );
  });
};

export const getWalletNFTs = async (address, chain = 'eth') => {
  return new Promise(async (resolve) => {
    const nftResList = await fetch(
      `https://deep-index.moralis.io/api/v2/${address}/nft?chain=${chain}&format=decimal`,
      {
        headers: header,
        method: 'GET',
      },
    );
    const nftResListData = await nftResList.json();
    resolve(nftResListData);
  });
};

export const getWalletNFTCountByToken = async (address, chain = 'eth') => {
  return new Promise(async (resolve) => {
    const nftResList = await fetchNFTsCount(address, chain);
    // const nftResListData = await nftResList.json();
    resolve(nftResList);
  });
};

const fetchNFTsCount = async (
  address,
  chain = 'eth',
  nftCount = {},
  cursor = null,
) => {
  let url = `https://deep-index.moralis.io/api/v2/${address}/nft?chain=${chain}&format=decimal`;
  if (cursor) {
    url = `https://deep-index.moralis.io/api/v2/${address}/nft?chain=${chain}&format=decimal&cursor=${cursor}`;
  }
  const nftResList = await fetch(url, {
    headers: header,
    method: 'GET',
  });
  const nftResListData = await nftResList.json();
  for (let i = 0; i < nftResListData.result.length; i++) {
    const address = nftResListData.result[i]['token_address'];
    if (nftCount.hasOwnProperty(address)) {
      nftCount[address] = Number(nftCount[address]) + 1;
    } else {
      nftCount[address] = 1;
    }
  }
  if (nftResListData['cursor'] == '' || !nftResListData['cursor']) {
    // resolve(nftCount);
    return nftCount;
  }
  await sleep(1000);
  return await fetchNFTsCount(address, chain, nftCount, nftResListData['cursor']);
};
